package com.leonshiep.stock.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

@SuppressWarnings("serial")
public class WXServlet extends javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet {
	private static Logger logger = Logger.getLogger(WXServlet.class);

	private ApplicationContext context;

	public WXServlet() {
		super();
	}

	@Override
	public void init() throws ServletException {

		super.init();
		context = WebApplicationContextUtils
				.getRequiredWebApplicationContext(getServletContext());
		context.getBean("");

	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");

		logger.info(signature);
		logger.info(timestamp);
		logger.info(nonce);
		echostr = new String(echostr.getBytes("ISO-8859-1"), "utf-8");
		logger.info(echostr);

		PrintWriter writer = response.getWriter();
		writer.println(echostr);
		writer.close();
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");

		String ip = request.getRemoteAddr();
		logger.info("remote ip : " + ip);
		int port = request.getRemotePort();
		logger.info("remote port " + port);

		StringBuffer jb = new StringBuffer();
		String line = null;

		try {
			BufferedReader reader = request.getReader();
			while ((line = reader.readLine()) != null)
				jb.append(new String(line.getBytes("ISO-8859-1"), "utf-8"));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		String requestBody = jb.toString();
		logger.info("Request Message : " + requestBody);


	}

	public static void main(String[] args) {
		logger.info("test");
	}

}